<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script src="https://cdn.bootcss.com/vue/2.5.15/vue.min.js"></script>
  <script>
    var app = new Vue({
      el: '#app',
      data: {},
      async mounted () {
        let params = ['apple', 'banana', 'orange']
        let result = []

        // 1.不应该每个请求都依次 await，每次依赖接口请求返回
        // for (let i = 0; i < params.length; i++) {
        //   await this.fetchBox(param[i])
        //   result.push(res)
        // }
        // Promise是构造函数形式，包裹异步操作：resolve（解决）reject（拒绝）
        // 回调函数和Promise函数的区别
        await params.map(async (param) => {
          const res = await this.fetchBox(param)
          result.push(res)
        })

        console.log(result)
        // 2.而是将同类的请求放到Promise.all()中去
        // let pool = params.map(param => {
        //   return fetchBox(param)
        // })

        // 3.尝试用Promise.all去执行遍历循环
        // let promiseResult = Promise.all(params.map(param => {
        //   return fetchBox(param)
        // }))
      },
      methods: {
        // 先定义方法
        async fetchBox (param) {
          return await new Promise((resolve, reject) => {
            setTimeout(() => {
              let box = {}
              box[param] = [1, 2, 3]
              resolve(box)
            }, 5000);
          })
        }
      }
    });
  </script>
</html>
